package org.jsbd.boss.action;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.common.ResponseUtils;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.dao.IThirdUserDAO;
import org.jsbd.boss.domian.channel.BaseResultVo;
import org.jsbd.boss.domian.channel.ChannelApkConfig;
import org.jsbd.boss.domian.channel.ThirdUserVo;
import org.jsbd.boss.enums.ApkBaseEnum;
import org.jsbd.boss.enums.ResponseEnum;
import org.jsbd.boss.service.IChannelApkInfoService;
import org.jsbd.boss.util.CacheKey;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/thirduser")
public class ThirdUserController {

	@Resource
	private IThirdUserDAO thirdUserDao;

	@Resource
	private RedisClient redisClient;

	@Resource
	private IChannelApkInfoService channelApkInfoService;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public void getUserList(String mark, HttpServletResponse response) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			if (StringUtils.isBlank(mark)) {
				resultVo.setStatus(ResponseEnum.FAIL.getStatus());
				resultVo.setMessage("请求参数非法!");
			} else {
				ChannelApkConfig apkConfig = channelApkInfoService.selectChannelApkConfig(mark);
				Integer base = apkConfig.getBase();
				int baseApkId = 0;
				if (base == ApkBaseEnum.OTHER.getType()) {
					baseApkId = apkConfig.getId();
				} else {
					baseApkId = base;
				}
				ThirdUserVo user = getUser(baseApkId);
				resultVo.setData(user);
			}
		} catch (Exception e) {
			resultVo.setMessage(e.getMessage());
			resultVo.setStatus(ResponseEnum.ERROR.getStatus());
		}
		ResponseUtils.renderJson(response, resultVo.toString());
	}

	private ThirdUserVo getUser(int baseApkId) {
		String key = CacheKey.THIRD_USER_LIST + baseApkId;
		ThirdUserVo user = (ThirdUserVo) redisClient.pollFromQueue(key);
		if (user == null) {
			if (redisClient.evalSetNx(key + "_LOCK", 30)) {
				List<ThirdUserVo> list = thirdUserDao.selectUsers(baseApkId);
				if (list != null && list.size() > 0) {
					for (ThirdUserVo userVo : list) {
						redisClient.putToQueue(key, userVo);
						userVo.setStatus(1);
					}
					thirdUserDao.batchUpdateUser(list);
				}
				user = (ThirdUserVo) redisClient.pollFromQueue(key);
			}
		}
		return user;

	}

}
